package com.himiotech.core.project.web.support;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import com.himiotech.core.framework.helper.constant.UserConstants;
import com.himiotech.core.framework.helper.exception.HimioException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * created by Wuwenbin on 2018/7/31 at 20:43
 *
 * @author wuwenbin
 */
@Slf4j
@Controller
@RequestMapping("/captcha")
public class EasyCaptchaController {


    @GetMapping("/captchaImage")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/gif");

        String type = request.getParameter("type");
        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 设置类型，纯数字、纯字母、字母数字混合
        if ("math".equals(type)) {
            specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        } else if ("char".equals(type)) {
            specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
        }
        specCaptcha.setLen(5);

        // 验证码存入session
        String capText = specCaptcha.text().toLowerCase();
        session.setAttribute(UserConstants.EASY_CAPTCHA_CODE_SESSION_KEY, capText);

        log.info("输出验证码：[{}]", capText);
        try {
            // 输出图片流
            specCaptcha.out(response.getOutputStream());
        } catch (Exception e) {
            throw new HimioException(e);
        }
    }
}
